package org.jeecg.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.oms.entity.OmsInquiryRuleValue;
import org.jeecg.modules.oms.mapper.OmsInquiryRuleValueMapper;
import org.jeecg.modules.oms.service.IOmsInquiryRuleValueService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 询单规则值服务实现
 */
@Slf4j
@Service
public class OmsInquiryRuleValueServiceImpl extends ServiceImpl<OmsInquiryRuleValueMapper, OmsInquiryRuleValue> implements IOmsInquiryRuleValueService {

    @Override
    public List<OmsInquiryRuleValue> getValuesByRuleId(String ruleId) {
        return baseMapper.getValuesByRuleId(ruleId);
    }

    @Override
    public boolean deleteByRuleId(String ruleId) {
        try {
            return this.remove(new QueryWrapper<OmsInquiryRuleValue>().eq("rule_id", ruleId));
        } catch (Exception e) {
            log.error("删除规则值失败", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSaveValues(String ruleId, List<String> values) {
        try {
            if (values == null || values.isEmpty()) {
                return true;
            }

            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String currentUser = loginUser != null ? loginUser.getUsername() : "system";
            Date now = new Date();

            List<OmsInquiryRuleValue> ruleValues = new ArrayList<>();
            for (int i = 0; i < values.size(); i++) {
                String value = values.get(i);
                if (value != null && !value.trim().isEmpty()) {
                    OmsInquiryRuleValue ruleValue = new OmsInquiryRuleValue();
                    ruleValue.setId(UUIDGenerator.generate());
                    ruleValue.setRuleId(ruleId);
                    ruleValue.setValue(value.trim());
                    ruleValue.setSortNo(i + 1);
                    ruleValue.setEnabled(1);
                    ruleValue.setDelFlag(0);
                    ruleValue.setCreateBy(currentUser);
                    ruleValue.setCreateTime(now);
                    ruleValues.add(ruleValue);
                }
            }

            if (!ruleValues.isEmpty()) {
                int result = baseMapper.batchInsert(ruleValues);
                return result > 0;
            }

            return true;
        } catch (Exception e) {
            log.error("批量保存规则值失败", e);
            throw new RuntimeException("批量保存规则值失败: " + e.getMessage());
        }
    }
}
